import Vue from 'vue';
import VueRouter from 'vue-router';
import baiduPush from '../utils/baiduStatistics';
Vue.use(VueRouter);

// 通过扫描方式加载路由
function loadRoutes() {
	let routes = [];
	const routerContext = require.context('./modules', false, /.js$/);
	routerContext.keys().forEach(route => {
		if (route.startsWith('./index')) return;
		const routerModule = routerContext(route);
		routes = [...routes, ...(routerModule.default || routerModule)];
	});
	return routes;
}

const routes = [
	{
		path: '/',
		name: 'bwbt',
		meta: {
			title: '赚分享',
			keepAlive: true
		},
		component: () => import('@/views/bwbt/index.vue')
	},
	{
		path: '/bwbt-limit',
		name: 'bwbt-limit',
		meta: {
			title: '限时限量抢购',
			keepAlive: true
		},
		component: () => import('@/views/bwbt/moreLimit.vue')
	},
	{
		path: '/h5-red-package',
		name: 'red-package',
		meta: {
			title: '领红包',
			keepAlive: true
		},
		component: () => import('@/views/red-package/index.vue')
	},
	{
		path: '/search-coupon',
		name: 'search-coupon',
		meta: {
			title: '搜券',
			keepAlive: true
		},
		component: () => import('../views/index/index.vue')
	},
	...loadRoutes()
];

// 创建项目路由
const router = new VueRouter({
	mode: 'hash',
	base: process.env.BASE_URL,
	routes
});

// 路由跳转前拦截
router.beforeEach((to, from, next) => {
	next();
});
router.afterEach((to, form) => {
	// 记录来自首页跳转推送百度
	if (form.name == 'index') {
		baiduPush('首页点击事件', '点击', '进入' + to.meta.title);
	}
	// 记录来自分类跳转推送百度
	if (form.name == 'goodsSort') {
		baiduPush('分类点击事件', '点击', '进入' + to.meta.title + `[${to.query.keyWord ? to.query.keyWord : ''}]`);
	}
	// 记录来自商品详情跳转推送百度
	if (form.name == 'goodsDetail') {
		baiduPush('商品分享好友', '点击', to.meta.title);
	}
	// 记录来自个人中心跳转推送百度
	if (form.name == 'memberCenter') {
		baiduPush('个人中心', '点击', '进入' + to.meta.title);
	}

	window.BestpayHtml5.APP.setTitleBar({
		title: {
			text: to.meta.title
		}
	});
});
export default router;
